package com.yz.group1.group_1.service.impl;

import com.yz.group1.group_1.entity.UserBook;
import com.yz.group1.group_1.mapper.UserBookMapper;
import com.yz.group1.group_1.service.UserBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class UserBookServiceImpl implements UserBookService {
    @Autowired
    private UserBookMapper userBookMapper;

    @Override
    @Transactional
    public UserBook createBooking(UserBook userBook) {
        userBook.setStatus(0); // 初始状态为待确认
        userBookMapper.insert(userBook);
        return userBook;
    }

    @Override
    @Transactional
    public boolean cancelBooking(Long bookingId) {
        UserBook booking = userBookMapper.selectById(bookingId);
        if (booking != null && booking.getStatus() == 0) {
            return userBookMapper.updateStatus(bookingId, 2) > 0;
        }
        return false;
    }

    @Override
    public List<UserBook> getPatientBookings(Long patientId) {
        return userBookMapper.selectByPatientId(patientId);
    }

    @Override
    public List<UserBook> getDoctorSchedule(Long doctorId, String date) {
        try {
            Date bookDate = new SimpleDateFormat("yyyy-MM-dd").parse(date);
            return userBookMapper.selectByDoctorAndDate(doctorId, bookDate);
        } catch (ParseException e) {
            throw new RuntimeException("日期格式错误");
        }
    }

    @Override
    public UserBook getBookingDetail(Long bookingId) {
        return userBookMapper.selectById(bookingId);
    }
}